package com.grape.springbootgradle20220520.data_formate;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author pan_jin
 * @Description: $
 * @Date: 2022/5/26 9:25
 * @Version: 1.0.0
 * @Slogan: 梦想还是要有的万一实现了呢
 */
public class XmlDemo {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
        InputStream inputStream = XmlDemo.class.getResourceAsStream("/book.xml");
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document = builder.parse(inputStream);

        printNode(document,0);
    }

    static void printNode(Node node, int indent) {
        for (int i = 0; i < indent; i++) {
            System.out.println(" ");

        }
        switch (node.getNodeType()) {
            case Node.DOCUMENT_NODE:
                System.out.println("document：" + node.getNodeName());
                break;
            case Node.ELEMENT_NODE:
                System.out.println("element:" + node.getNodeName());
                break;
            case Node.ATTRIBUTE_NODE:
                System.out.println("nodeName:" + node.getNodeName() + "value:" + node.getNodeValue());
                break;
            case Node.TEXT_NODE:
                System.out.println("nodeName:" + node.getNodeName() + "nodeValue:" + node.getNodeValue());
            default:
                System.out.println("nodeType:" + node.getNodeValue() + "nodeName:" + node.getNodeName());
        }
        for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
            printNode(child, indent + 1);
        }

    }
}
